R/binomial distributions.R

## Binomial distributions (page 318+)----
dbinom(x=10, size=15, prob=0.83) #Example from page 320. This answers the question: What's the probability of exactly 10 people wearing seatbelts? This function can also take a vector for argument x.
#Compare with manual method on page 320:
nChooseK <- function(n, k){
  factorial(n)/(factorial(k)*factorial(n-k))
}
nChooseK(15,10)*0.83^10*0.17^5

#See also:
(result <- pbinom(q=10,size=15,prob=0.83)) #Cumulative probability function; answers the question: What's the probability of 10 or fewer people wearing seatbelts?
#Compare pbinom() with:
dbinom(0, size=15, prob=0.83) +
  dbinom(1, size=15, prob=0.83) + 
  dbinom(2, size=15, prob=0.83) + 
  dbinom(3, size=15, prob=0.83) + 
  dbinom(4, size=15, prob=0.83) + 
  dbinom(5, size=15, prob=0.83) + 
  dbinom(6, size=15, prob=0.83) + 
  dbinom(7, size=15, prob=0.83) + 
  dbinom(8, size=15, prob=0.83) + 
  dbinom(9, size=15, prob=0.83) +
  dbinom(10, size=15, prob=0.83)
#Note also, you can control the tail of the cumulative probability distribution that is return with the optional argument, lower = TRUE/FALSE.
pbinom(q=12,size=15,prob=0.83, lower=FALSE) #Page 320. This answers the question: What's the probability of 13 or more people wearing seatbelts? Notice that q = 12, since we want 13 OR more.

qbinom(p=result,size=15,prob=0.83) #This returns the quantile (percentile) of a binomial distribution with size = n and stated probability. Note the relationship between pbinom() and qbinom(). This function will return the random variable value based on the probability, where as pbinom() returns the probability based on the random variable value.

rbinom(n= 15, size=20, p=0.83) #Generate data with a binomial distribution. We use this function to generate n independent random variables, each of which is the result of some number of trials (size) with the stated probability. rbinom(n= 15, size=20, p=0.83) means: perform a test 20 times where the probability of success is 0.83. Return the number of successes across the 20 trials. Repeat this process 15 times.

rbinom(n= 15, size=1, p=0.5) #If the size = 1, this returns bernoulli trials. Using 0.5 as the probability is like simulating coin tosses.
18kimn/yalestats documentation built on May 9, 2019, 2:17 a.m.